#include "ff.h"
#include "lrc_api.h"
#include "lrc_util.h"
#include "db_format.h"

#ifdef WIN32
#include <stdio.h> 
#include "assert.h"
#define MALLOC malloc
#define FREE free
#else
#include "sys_types.h"
#define MALLOC OAL_malloc
#define FREE OAL_free
#define assert(...)
#endif

FRESULT lrc_ffopen(FIL ** fp, const char* path, unsigned char mode)
{
	FRESULT res;

	assert(*fp == 0);
	*fp = (FIL*)MALLOC(sizeof(FIL));
	if(0==*fp)
	{
		return FR_INT_ERR;
	}
	
	res = f_open(*fp, path, mode);

	if(FR_OK != res)
	{
		FREE(*fp);
		*fp = 0;
	}

	return res;
}

FRESULT lrc_ffclose(FIL ** fp)
{
	if(*fp)
	{
		FRESULT res = f_close(*fp);
		FREE(*fp); 
		*fp = 0;
		return res;
	}
	return FR_OK;
}

void lrc_str_to_utf8(const unsigned char * in, unsigned char * out, int len, int format)
{
	int out_len = 0;
	int in_len = strlen((char*)in);

	switch(format)
	{
	case ASCII_FORMAT			:
	case UTF_8_NOBOM_FORMAT		:
	case UTF_8_BOM_FORMAT		:
		if(in_len < len-1)
		{
			strcpy((char*)out, (char*)in);
		}
		else
		{
			memcpy(out, in, len);
			if((((out[len-1] & 0xF0) == 0xE0)) || ((out[len-1] & 0xF0) == 0xC0))
				out[len-1] = 0;
			else if((((out[len-2] & 0xF0) == 0xE0)) || ((out[len-2] & 0xF0) == 0xC0))
				out[len-2] = 0;
			else if((((out[len-3] & 0xF0) == 0xE0)) || ((out[len-3] & 0xF0) == 0xC0))
				out[len-3] = 0;
			else
				out[len-1] = 0;
		}
		break;

	case ANSI_FORMAT			:
		out_len = db_gb2312_to_utf8(in, in_len, out, len-1);
		out[out_len] = 0;
		break;

	case UTF_16_L_ENDIAN_FORMAT	:
		out_len = UTF_16LE_to_utf8(in, in_len, out, len-1);
		out[out_len] = 0;
		break;

	case UTF_16_B_ENDIAN_FORMAT	:
		out_len = UTF_16BE_to_utf8(in, in_len, out, len-1);
		out[out_len] = 0;
		break;

	case UTF_32_L_ENDIAN_FORMAT	:
		assert(0);
		break;

	case UTF_32_B_ENDIAN_FORMAT	:
		assert(0);
		break;

	case ERROR_FORMAT			:
		assert(0);
		break;

	default						:
		assert(0);
		break;
	}
}
